<?php
class Reference_TourController extends Agitum_Controller_Action
{
    public function completeAction ()
    {
    	$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout()->disableLayout();

    	$term = $this->_request->getParam('query', null);
    	if ( !$term ) return;

    	$slot = new Agitum_Model_Cache_Slot_Tour_List();
		$tour = $slot->load();
		if (!$tour) {
			$obj = new Agitum_Model_Tour();
			$tour = $obj->fetchMap();
			foreach( $tour as $id => $row ) {
				$slot->addTag(new Agitum_Model_Cache_Tag_Tour($id));
			}
			$slot->addTag(new Agitum_Model_Cache_Tag_Tour_List());
			$slot->save($tour);
		}
		
		$filter = function($item) use ($term) 
		{
			if(stristr($item['title'], $term)) return true;
			return false;
		};
		
		$data = array();
		$suggest = array();
		
		foreach ( array_filter($tour, $filter) as $item ) {
			$suggest[] = $item['title'];
			$data[] = $item['id'];
		} 

//    	$this->_response->setHeader('Content-Type', 'application/json');
		echo Zend_Json::encode(array('query' => $term, 'suggestions' => $suggest, 'data' => $data ));
    }
}